#!/bin/bash
set -eu
umask 077
resources="$(cd "$(dirname "$0")/../Resources" && pwd)"
if ! /usr/bin/osascript -e 'display dialog "WAVLoader Studio auf diesem Mac einrichten? Python, Oberfläche, FFmpeg und weitere Komponenten werden automatisch geladen und geprüft. Internetverbindung und macOS 13 oder neuer sind erforderlich. Bestehende Musik bleibt erhalten." with title "WAVLoader Setup" buttons {"Abbrechen", "Installieren"} default button "Installieren" cancel button "Abbrechen"'; then exit 0; fi
case "$(uname -m)" in
 arm64) python_url='https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.13.18%2B20261026-aarch64-apple-darwin-install_only.tar.gz'; python_sha='e5af2fde6a937a0e0c795a0c595c4efb70578d57463a2657c819992b9b9acbac' ;;
 x86_64) python_url='https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.13.18%2B20261026-x86_64-apple-darwin-install_only.tar.gz'; python_sha='708be9e7df297f68bdae589ea9e62a621db5abe7708f79e851c41410347452d1' ;;
 *) /usr/bin/osascript -e 'display alert "Diese Mac-Architektur wird nicht unterstützt."'; exit 1 ;;
esac
mkdir -p "$HOME/Library/Logs"
log="$HOME/Library/Logs/WAVLoader-Setup.log"
temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/wavloader.XXXXXXXX")"
trap 'rm -rf "$temporary"' EXIT
/usr/bin/osascript -e 'display notification "Komponenten werden eingerichtet. Das kann einige Minuten dauern." with title "WAVLoader Setup"' || true
status=0
(
 /usr/bin/curl --fail --location --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 30 --max-time 900 --output "$temporary/python.tar.gz" "$python_url"
 actual="$(/usr/bin/shasum -a 256 "$temporary/python.tar.gz")"
 [ "${actual%% *}" = "$python_sha" ] || { echo 'Python-Prüfsumme stimmt nicht.'; exit 1; }
 /usr/bin/tar -xzf "$temporary/python.tar.gz" -C "$temporary"
 "$temporary/python/bin/python3" -B "$resources/macos_install.py" "$resources" "$temporary/python"
) > "$log" 2>&1 || status=$?
if [ "$status" -ne 0 ]; then
 /usr/bin/osascript -e 'display dialog "Einrichtung fehlgeschlagen. Details stehen in Library/Logs/WAVLoader-Setup.log. Bitte Verbindung und freien Speicher prüfen; bei einer Prüfsummenabweichung ein aktuelles Setup verwenden." with title "WAVLoader Setup" buttons {"Schließen", "Protokoll öffnen"} default button "Protokoll öffnen"' | /usr/bin/grep -q 'Protokoll öffnen' && /usr/bin/open "$log"
 exit "$status"
fi
/usr/bin/osascript -e 'display dialog "WAVLoader wurde in deinem Applications-Ordner installiert und gestartet. Die normale App öffnet ohne Terminalfenster." with title "WAVLoader Setup" buttons {"Fertig"} default button "Fertig"'
